package com.sky.common.security.service;

import cn.hutool.core.util.StrUtil;
import com.sky.admin.api.entity.ReadClubStudentEntity;
import com.sky.admin.api.feign.RemoteUserService;
import com.sky.common.core.constant.CacheConstants;
import com.sky.common.core.constant.CommonConstants;
import com.sky.common.core.constant.SecurityConstants;
import com.sky.common.core.util.R;
import com.sky.common.core.util.RetOps;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@RequiredArgsConstructor
public class PigxAppUserNormalDetailsServiceImpl implements PigUserDetailsService {

	private final RemoteUserService remoteUserService;

	private final CacheManager cacheManager;

	/**
	 * 手机号登录
	 *
	 * @param username 手机号
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		Cache cache = cacheManager.getCache(CacheConstants.APP_USER_DETAILS);
		if (cache != null && cache.get(username) != null) {
			return (PigUser) cache.get(username).get();
		}

		R<ReadClubStudentEntity> result = remoteUserService.appUserNameQuery(username,
				SecurityConstants.FROM_IN);

		UserDetails userDetails = getAppUserDetails(result);
		if (cache != null) {
			cache.put(username, userDetails);
		}
		return userDetails;
	}

	private UserDetails getAppUserDetails(R<ReadClubStudentEntity> result) {
		ReadClubStudentEntity info = RetOps.of(result).getData()
				.orElseThrow(() -> new UsernameNotFoundException("用户不存在"));

		// 构造security用户
		return new PigUser(info.getUserId(), 0L, info.getUserName(),
				SecurityConstants.BCRYPT + info.getPassword(), info.getParentOnePhone(), true, true,
				true, StrUtil.equals(info.getLockFlag(), CommonConstants.STATUS_NORMAL),
				AuthorityUtils.NO_AUTHORITIES, info.getUserNameEn());
	}

	/**
	 * check-token 使用
	 *
	 * @param pigUser user
	 * @return
	 */
	@Override
	public UserDetails loadUserByUser(PigUser pigUser) {
		return this.loadUserByUsername(pigUser.getUsername());
	}

	/**
	 * 是否支持此客户端校验
	 *
	 * @param clientId 目标客户端
	 * @return true/false
	 */
	@Override
	public boolean support(String clientId, String grantType) {
		return SecurityConstants.CLIENT_TYPE_WECHAT_SIGN_CLIENT.equals(clientId);
	}

	/**
	 * 排序值
	 *
	 * @return 排序值
	 */
	@Override
	public int getOrder() {
		return 10;
	}

}

